//
//  linkListMap.swift
//  SetAndMap
//
//  Created by lhc on 2024/7/21.
//

import Foundation




class LinkListMap<K: Comparable, V: Comparable>: MyMap {
    
    class Node {
        let key: K?
        let value: V?
        var next: LinkListMap.Node?
        
        init(key: K? = nil, value: V? = nil, next: LinkListMap.Node? = nil) {
            self.key = key
            self.value = value
            self.next = next
        }
    }
    
    private var dummyNode = Node()
    private var size = 0
    
    func getSize() -> Int {
        return self.size
    }
    
    func isEmpty() -> Bool {
        return self.size == 0
    }
    
    func getValueBy(key: K) -> V? {
        var pre: Node? = self.dummyNode
        while pre?.next != nil {
            if let k = pre?.next?.key {
                if k == key {
                    return pre?.next?.value
                }
            }
            pre = pre?.next
        }
        return nil
    }
    
    /// 设置K-V值
    func setValueBy(key: K, value: V) {
        var pre: Node? = self.dummyNode
        while pre?.next != nil {
            if let k = pre?.next?.key {
                if k == key {
                    // 找到了对应k的node 就是pre.next
                    break
                }
            }
            
            // 没找到就找下一个node
            pre = pre?.next
        }
        
        // 到这里可能是pre.next是我们要找的key, 也可能是map里没有对应的key, pre.next == nil
        let node = Node(key: key, value: value)
        if let oldNode = pre?.next {
            // 这种情况pre.next存在就是我们要找的key的node
            node.next = oldNode.next
            pre?.next = node
            oldNode.next = nil
        }else {
            // pre.next不存在，我们要添加新的node
            pre?.next = node
        }
        
        self.size += 1
        
    }
    
    func remove(key: K) -> V? {
        var pre: Node? = self.dummyNode
        while pre?.next != nil {
            if let k = pre?.next?.key {
                if k == key {
                    // 找到对应的要移除的key
                    
                    let node = pre?.next
                    pre?.next = node?.next
                    node?.next = nil
                    
                    self.size -= 1
                    return node?.value
                }
            }
            pre = pre?.next
        }
        return nil
    }
    
}

extension LinkListMap: CustomStringConvertible {
    var description: String {
        
        var pre: Node? = self.dummyNode
        var resultsArray = [(K, V)]()
        while pre?.next != nil {
            if let next = pre?.next {
                if let key = next.key {
                    if let value = next.value {
                        resultsArray.append((key, value))
                    }
                }
                
            }
            pre = pre?.next
        }
        
        return "\(resultsArray)"
    }
    
    
}

